{% extends "base.html" %}

{% block title %}K8s管理{% endblock %}

{% block head %}
  {{ super() }}
  <!-- DataTables -->
  <link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
{% endblock %}


{% block content %}
  <!-- 页面头 -->
  <section class="content-header">
    <!--头部标题-->
    <h1>
      集群概况
      <!--    <small>advanced tables</small>-->
    </h1>
    <!--面包屑-->
    <ol class="breadcrumb">
      <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
      <li><a href="/blues/blues/clusterler/cluster"> 集群管理</a></li>
      <li class="active">概况</li>
    </ol>
  </section>

  <!-- 页面内容 -->
  <section class="content">

    <div class="row">
      <div class="col-md-12">
        <!--顶部控制栏-->
        <form class="form-inline" style="margin-bottom: 10px">
          <div class="form-group">
            <label for="selectCluster"> <span style="color: red">*</span> 集群</label>
            <select class="form-control" id="selectCluster" name="cluster_id" required>
              <option value="" selected>--请选择--</option>
            </select>
          </div>

          <div class="form-group pull-right">
            {% if session['role'] in ['admin','superadmin'] %}
              <button id="btn_add_cluster_modal" type="button" class="btn btn-primary" data-toggle="modal"
                      data-target="#addClusterModal"><i class="fa fa-plus"></i> 添加集群
              </button>
              <a class="btn btn-warning" href="#" role="button" id="btn_create_yaml" disabled="disabled"><i
                class="fa fa-edit"></i> 从Yaml创建</a>
            {% endif %}
            <!--          <a class="btn btn-primary" href="#" role="button" id="btn_ingress" disabled="disabled">Ingress</a>-->
          </div>
        </form>
        <!--系统可用性-->
        {#      <div class="box">#}
        {#        <div class="box-header with-border">#}
        {#          <h3 class="box-title">系统可用性</h3>#}
        {##}
        {#          <div class="box-tools pull-right">#}
        {#            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>#}
        {#            </button>#}
        {#            <div class="btn-group">#}
        {#              <button type="button" class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown">#}
        {#                <i class="fa fa-wrench"></i></button>#}
        {#              <ul class="dropdown-menu" role="menu">#}
        {#                <!--                <li><a href="#" id="btn_add_cluster_modal1" data-toggle="modal" data-target="#addClusterRelatedInstance">添加关联系统</a></li>-->#}
        {#                <li><a href="#" id="btn_add_cluster_modal1">添加关联系统</a></li>#}
        {#              </ul>#}
        {#            </div>#}
        {#            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>#}
        {#          </div>#}
        {#        </div>#}
        {#        <div class="box-body" id="prom_aval_box">#}
        {#        </div>#}
        {#      </div>#}
        <!--集群信息-->
        <div class="box">
          <div class="box-header with-border">
            <h3 class="box-title">集群信息</h3>
            <div class="box-tools pull-right">
              <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
              </button>
              <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
            </div>
          </div>
          <div class="box-body">
            <div class="col-md-2 col-xs-4">
              <p>节点数</p>
              <h2 id="nodes"></h2>
            </div>
            <div class="col-md-2 col-xs-4">
              <p>CPU核心总数</p>
              <h2 id="cores"></h2>
            </div>

            <div class="col-md-2 col-xs-4">
              <p>内存总大小（GB）</p>
              <h2 id="memory_size"></h2>
            </div>

            <div class="col-md-2 col-xs-4">
              <p>磁盘总大小（GB）</p>
              <h2 id="disk_size"></h2>
            </div>

            <div class="col-md-2 col-xs-4">
              <p>Service总数</p>
              <h2 id="services"></h2>
            </div>

            <div class="col-md-2 col-xs-4">
              <p>POD总数/上限</p>
              <h2><span id="running_pods"></span><span id="pods"></span></h2>
            </div>


          </div>

        </div>
        <!--集群监控图形-->
        <div class="box">
          <div class="box-header with-border">
            <h3 class="box-title">集群监控</h3>
            <div class="box-tools pull-right">
              <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
              </button>
              <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
            </div>
          </div>
          <div class="box-body">
            <div class="col-md-4">
              <div id="chart_cpu" style="height:250px"></div>
            </div>
            <div class="col-md-4">
              <div id="chart_mem" style="height:250px"></div>
            </div>
            <div class="col-md-4">
              <div id="chart_disk" style="height:250px"></div>
            </div>
            <div class="col-md-12">
              <div id="chart_net" style="height:250px"></div>
            </div>
          </div>
        </div>
        <!--节点表格-->
        <div class="box">
          <div class="box-header with-border">
            <h3 class="box-title">节点概览</h3>
            <div class="box-tools pull-right">
              <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
              </button>
              <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
            </div>
          </div>
          <div class="box-body table-responsive">
            <table id="example1" class="table-hover table-bordered table-condensed table-striped"
                   style="width:100%;font-size: 90%">
              <thead>
              <tr>
                <th>节点</th>
                <th>角色</th>
                <th>状态</th>
                <th>Pods上限</th>
                <th>规格</th>
                <th>CPU</th>
                <th>内存</th>
                <th>存储</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody id="tbody">
              </tbody>
            </table>
          </div>
          <!-- /.box-body -->
        </div>
        <!--数据库表格-->
        <div class="box">
          <div class="box-header with-border">
            <h3 class="box-title">数据库</h3>
            <div class="box-tools pull-right">
              <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
              </button>
              <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
            </div>
          </div>
          <div class="box-body table-responsive">
            <table id="table_mysql" class="table-hover table-bordered table-condensed table-striped"
                   style="width:100%;font-size: 90%">
              <thead>
              <tr>
                <th>实例名</th>
                <th>运行时间</th>
                <th>QPS</th>
                <th>连接数</th>
                <th>慢查询</th>
                <th>网络入</th>
                <th>网络出</th>
              </tr>
              </thead>
              <tbody id="tbody_mysql">
              </tbody>
            </table>
          </div>
          <!-- /.box-body -->
        </div>
      </div>
    </div>

  </section>
  <!-- /.页面内容 -->

  <!-- 模态框：添加集群 -->
  <div class="modal fade" id="addClusterModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="addModalLabel">添加K8s集群</h4>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group">
              <a href="/static/html/md.html" target="_blank">如何获取集群参数？</a>
            </div>
            <div class="form-group">
              <label for="cluster-name" class="control-label"><span style="color: red">*</span> 集群名称:</label>
              <input type="text" class="form-control" id="cluster-name">
            </div>
            <div class="form-group">
              <label for="api-server" class="control-label"><span style="color: red">*</span> Api Server:</label>
              <input type="text" class="form-control" id="api-server">
            </div>
            <div class="form-group">
              <label for="token" class="control-label"><span style="color: red">*</span> Token:</label>
              <input type="text" class="form-control" id="token">
            </div>
            <div class="form-group">
              <label for="prom-server" class="control-label">Prom Server:</label>
              <input type="text" class="form-control" id="prom-server">
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-warning" id="btn_cluster_submit">确认</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 模态框：添加关联系统 -->
  <div class="modal fade" id="addClusterRelatedInstance" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="addModalLabel1">集群添加关联系统</h4>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group">
              <label for="cluster-name2" class="control-label"><span style="color: red">*</span> 集群:</label>
              <input type="text" class="form-control" id="cluster-name2" disabled="disabled">
            </div>
            <div class="form-group">
              <label for="selectProm" class="control-label"><span style="color: red">*</span> 所属Prom:</label>
              <select class="form-control" id="selectProm">
                <option value="" selected>--请选择--</option>
              </select>
            </div>
            <div class="form-group">
              <label for="selectInstance" class="control-label"><span style="color: red">*</span> 系统:</label>
              <select class="form-control" id="selectInstance">
                <!--          <option>&#45;&#45;请选择表单&#45;&#45;</option>-->
              </select>
            </div>

          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-warning" id="btn_cluster_instance_add">确认</button>
        </div>
      </div>
    </div>
  </div>
{% endblock %}


{% block script %}
  <script src="/static/js/echarts.min.js"></script>


  <!-- DataTables -->
  <script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
  <script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
  <!-- Page specific script -->
  <script type="text/javascript">
      // 解析URL
      var pathName = window.document.location.pathname;
      var pathList = pathName.split("/")        // 例如 /cluster/ 被解析为 ['', 'cluster', '']
      console.log(pathList)
      var cluster_id = pathList[2]


      // 检测本地是否保存变量
      if (cluster_id > 0) {
          console.log("save cluster_id to session_storage")
          sessionStorage.setItem("cluster_id", cluster_id)
      } else {
          console.log("no cluster_id in url")
          cluster_id = sessionStorage.getItem("cluster_id")
          // 设置默认值
          if (cluster_id == null) {
              cluster_id = 1
              sessionStorage.setItem("cluster_id", cluster_id)
          }
      }
      console.log("cluster ID is: ", cluster_id)


      // 添加集群modal中确定按钮
      $('#btn_cluster_submit').click(function (e) {
          e.preventDefault()
          var payload = {
              name: $('#cluster-name').val(),
              apiserver: $('#api-server').val(),
              token: $('#token').val(),
              prom: $('#prom-server').val()
          }

          $.ajax({
              method: 'POST',
              url: '/api/add_cluster/',
              data: JSON.stringify(payload),
              headers: {'Content-Type': 'application/json; charset=utf-8'},
              success: function (result) {
                  console.log(result)
                  // alert(result.code)
                  $('#addClusterModal').modal('hide')
                  bootbox.alert(result.message, function () {
                      if (result.code === 200) {
                          setTimeout(function () {
                              location.reload()
                          }, 250)
                      }
                  })
              }
          })

      })


      // 检测集群选择变化，则跳转到对应URL
      $("#selectCluster").change(function () {
          let s = $('#selectCluster').val().trim()
          if (s === '' || s === null || s === undefined) {
              // 判断字符串为空
              $('#btn_create_yaml').attr('disabled', 'disabled')
          } else {
              location.href = '/cluster/' + s
          }
      })

      $('#btn_create_yaml').click(function () {
          if ($('#btn_create_yaml').attr('disabled') != 'disabled') {
              location.href = '/cluster/createfromyaml?cluster_id=' + cluster_id
          }
      })


      function refreshTable_v2(cluster_id) {
          $('#btn_create_yaml').removeAttr('disabled')

          //接口调用，并填充数据Table


          // var url = '/api/v2/cluster/' + cluster_id + '/nodes'
          // $.get(url, function (data) {
          //     console.log(data)
          //     $('#tbody').find('td').remove()
          //     for (let i in data) {
          //         let url_mon = `/cluster/node_monitor?cluster_id=${cluster_id}&instance=${i}&time_range=hour`
          //         let text = '<tr>'
          //         text += '<td>' + i + '</td>'
          //         text += '<td>' + data[i]['role'] + '</td>'
          //         text += '<td>' + data[i]['conditions'] + '</td>'
          //         text += '<td>' + data[i]['pods'] + '</td>'
          //         text += '<td>' + data[i]['specs'] + '</td>'
          //         text += '<td>' + data[i]['cpu_use'] + '</td>'
          //         text += '<td>' + data[i]['mem_use'] + '</td>'
          //         text += '<td>' + data[i]['disk_use'] + '</td>'
          //         text += '<td><a href=' + url_mon + '>监控</a></td>'
          //         text += '</tr>'
          //         $('#tbody').append(text)
          //     }
          //     // 填充完表格内容后，设置表格样式
          //
          //
          // });

          $('#example1').DataTable({
              ajax: '/api/v2/cluster/' + cluster_id + '/nodes',
              language: {
                  "url": "/static/language.json"
              },
              columns: [
                  {data: 'name'},
                  {data: 'role'},
                  {data: 'conditions'},
                  {data: 'pods'},
                  {data: 'specs'},
                  {data: 'cpu_use'},
                  {data: 'mem_use'},
                  {data: 'disk_use'},
                  {
                      data: null,
                      fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                          let url_mon = `/cluster/node_monitor?cluster_id=${cluster_id}&instance=${oData.name}&time_range=hour`
                          $(nTd).html("<a href='" + url_mon + "'>监控</a>");
                      }
                  },
              ],
              processing: true,
              paging: false,
              lengthChange: false,
              searching: false,
              ordering: true,
              order: [[1, 'asc'], [0, 'asc']],
              autoWidth: true,
              responsive: true,
          });
      }


      function timestamp2time(timestamp) {
          //直接用 new Date(时间戳) 格式转化获得当前时间
          var timestamp1 = new Date(timestamp * 1000);
          //再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式
          dateString = timestamp1.toLocaleDateString().replace(/\//g, "-").substr(5) + "\n" + timestamp1.toTimeString().substr(0, 5)
          return dateString
      }

      // function getPromDrawGauge(query_str, domId, title) {
      //     $.ajax({
      //         url: `/api/v1/cluster/${cluster_id}/prom/query?query=${query_str}`,
      //         success: function (data) {
      //             console.log(data)
      //             drawGauge(domId, data, title)
      //         }
      //     })
      // }

      function drawGauge(query_str, domId, title) {
          // 基于准备好的dom，初始化echarts实例
          var myChart = echarts.init(document.getElementById(domId));
          // 指定图表的配置项和数据
          let option = {
              title: {
                  left: 'center',
                  text: title,
                  textStyle: {
                      fontWeight: 'normal',
                      fontSize: 17,
                      lineHeight: 10,
                  }
              },
              tooltip: {
                  formatter: "{a}: {c}%"
              },
              series: [
                  {
                      name: title,
                      type: 'gauge',
                      radius: '100%',
                      center: ['50%', '61%'],
                      detail: {formatter: '{value} %'},
                      // data: [{
                      //     value: 0
                      // }],
                      axisLine: {
                          lineStyle: {
                              width: 30,
                              color: [
                                  [0.3, '#00a65a'],
                                  [0.7, '#f39c12'],
                                  [1, '#f56954']
                              ]
                          }
                      },
                      pointer: {
                          itemStyle: {
                              color: 'auto'
                          }
                      },
                      axisTick: {
                          distance: -30,
                          length: 8,
                          lineStyle: {
                              color: '#fff',
                              width: 1
                          }
                      },
                      splitLine: {
                          distance: -30,
                          length: 30,
                          lineStyle: {
                              color: '#fff',
                              width: 4
                          }
                      },
                      axisLabel: {
                          color: 'auto',
                          distance: 40,
                          fontSize: 13
                      },
                      detail: {
                          valueAnimation: true,
                          formatter: '{value} %',
                          color: 'auto'
                      },
                  }
              ]
          };
          // 使用刚指定的配置项和数据显示图表。
          myChart.setOption(option);

          // 调用prom接口，并渲染数据
          var a1 = $.ajax({
              url: `/api/v1/cluster/${cluster_id}/prom/query?query=${query_str}`,

          })

          $.when(a1).then(function (r1) {
              if (r1.status != 'success' || r1.data.result.length == 0) {
                  console.log(r1)
                  return
              }
              let data = parseFloat(r1.data.result[0].value[1]).toFixed(0)
              console.log(title, data)
              // console.log(r1)
              myChart.setOption({
                  series: [
                      {
                          data: [{
                              value: data
                          }],
                      }
                  ]
              })
          })
      }


      function draw2Lines(query_str, query_str2, domId, title) {
          // 基于准备好的dom，初始化echarts实例
          var myChart = echarts.init(document.getElementById(domId));
          // 指定图表的配置项和数据
          var option = {
              title: {
                  left: 'center',
                  text: title,
                  textStyle: {
                      fontWeight: 'normal',
                      fontSize: 17,
                      lineHeight: 40,
                  }
              },
              grid: {
                  top: '20%',
                  right: '2%',
                  left: '0%',
                  bottom: '2%',
                  containLabel: true
              },
              tooltip: {
                  trigger: 'axis',
                  // axisPointer: {
                  //     type: 'cross',
                  //     // label: {
                  //     //     backgroundColor: '#6a7985'
                  //     // }
                  // },
                  // formatter: function (params) {
                  //     // console.log(params)
                  //     var relVal = params[0].name
                  //     for (var i = 0, l = params.length; i < l; i++) {
                  //         relVal += `<br/>${params[i].marker}${params[i].seriesName}  ${params[i].value} kbps`
                  //     }
                  //     return relVal
                  // }
              },
              xAxis: {
                  type: 'category',
                  data: []
              },
              yAxis: {
                  type: 'value',
                  axisLabel: {
                      show: true,
                      //Y轴数值可添加百分号
                      formatter: '{value}',
                  },
              },
              series: [
                  {
                      name: '入流量',
                      // data: [],
                      type: 'line',
                      smooth: false,
                      symbol: 'none',//去掉小圆点
                  },
                  {
                      name: '出流量',
                      // data: [],
                      type: 'line',
                      smooth: false,
                      symbol: 'none',//去掉小圆点
                  }
              ]
          };

          // 使用刚指定的配置项和数据显示图表。
          myChart.setOption(option);

          // 刷新数据
          var u1 = $.ajax({
              url: `/api/v1/cluster/${cluster_id}/prom/query_range?time_range=hour&query=${query_str}`,
          })

          // 刷新数据2
          var u2 = $.ajax({
              url: `/api/v1/cluster/${cluster_id}/prom/query_range?time_range=hour&query=${query_str2}`,
          })

          $.when(u1, u2).then(function (a1, a2) {
              // console.log("a1 ", a1)
              // console.log("a2", a2)
              let date = [], data1 = [], data2 = [];
              let a1_values = a1[0].data.result[0].values
              let a2_values = a2[0].data.result[0].values
              for (let i = 0, len = a1_values.length; i < len; i++) {
                  // date.push(timestamp2time(a1_values[i][0]));
                  data1.push(parseFloat(a1_values[i][1]).toFixed(0));
              }
              for (let i = 0, len = a2_values.length; i < len; i++) {
                  date.push(timestamp2time(a2_values[i][0]));
                  data2.push(parseFloat(a2_values[i][1]).toFixed(0));
              }

              myChart.setOption({
                  xAxis: {
                      data: date
                  },
                  series: [
                      {
                          data: data1
                      },
                      {
                          data: data2
                      }
                  ]
              });
          })
      }

      // 检测到selectProm发生变化，动态填充selectInstance
      $('#selectProm').change(function () {
          console.log("changed")
          let prom_id = $('#selectProm').val()
          $("#selectInstance").find('option').remove();
          $("#selectInstance").append('<option value="">--请选择--</option>');
          $.get(`/api/prom/probe_endpoints_list?prom_id=${prom_id}`, function (data) {
              console.log(data)
              for (var i in data.data) {
                  $("#selectInstance").append('<option value="' + data.data[i].instance + '">' + data.data[i].instance + '</option>');
              }
          });

      })

      // 检测到点击添加关联系统确定按钮，进行判断
      $('#btn_cluster_instance_add').click(function (e) {
          // console.log("clicked")
          console.log("cluster id:", cluster_id)
          let prom_id = $('#selectProm').val()
          let instance = $('#selectInstance').val()
          // console.log(prom_id, instance)
          if (prom_id == "" || instance == null || instance == "" || cluster_id == null) {
              // console.log('bad ')
              alert("选择参数错误，请检查")
          }


          e.preventDefault()
          var payload = {
              prom_id: prom_id,
              instance: instance,
              cluster_id: cluster_id
          }
          // 后台添加集群关联系统
          $.ajax({
              method: 'POST',
              url: '/api/v1/cluster/add_instance',
              data: JSON.stringify(payload),
              headers: {'Content-Type': 'application/json; charset=utf-8'},
              success: function (result) {
                  console.log(result)
                  // alert(result.code)
                  $('#addClusterRelatedInstance').modal('hide')
                  bootbox.alert(result.message, function () {
                      if (result.code === 200) {
                          setTimeout(function () {
                              location.reload()
                          }, 250)
                      } else {
                          alert(result.message)
                      }
                  })
              }
          })


      })

      // 添加关联系统按钮，如果集群为选择，则打开modal
      $('#btn_add_cluster_modal1').click(function (e) {
          if (cluster_id == null) {
              e.preventDefault()
              alert('请先选择集群！')
              return
          }
          $('#addClusterRelatedInstance').modal('show')
      })


      function updateAvalNumber(prom_id, query_str, domId) {
          $.ajax({
              url: `/api/v1/prom/query?prom_id=${prom_id}&query=${query_str}`,
              success: function (data) {
                  num = parseFloat(data.data.result[0].value[1]).toFixed(2)
                  $(`#${domId}`).text(num)
                  if (num < 95) {
                      $(`#${domId}`).css("color", "orange")
                  }
                  if (num < 80) {
                      $(`#${domId}`).css("color", "red")
                  }
              }
          })
      }

      function drawAvalLines(prom_id, elemId, instance) {
          function draw(elemId, x, y1, y2) {
              // 基于准备好的dom，初始化echarts实例
              var myChart = echarts.init(document.getElementById(elemId));

              // 指定图表的配置项和数据
              var option = {
                  title: {
                      text: instance,
                      left: "center"
                  },
                  tooltip: {
                      trigger: 'axis',
                  },
                  grid: {
                      top: '20%',
                      right: '2%',
                      left: '2%',
                      bottom: '10%',
                      containLabel: true
                  },
                  xAxis: {
                      data: x
                  },
                  yAxis: [
                      {
                          type: 'value',
                          name: '延迟',
                          position: 'left',
                          axisLine: {
                              lineStyle: {
                                  color: '#5572C3'
                              }
                          },
                          axisLabel: {
                              formatter: '{value} s'
                          }
                      },
                      // {
                      //     type: 'value',
                      //     name: 'up',
                      //     min: 0,
                      //     // max: 1,
                      //     position: 'right',
                      //     axisLine: {
                      //         lineStyle: {
                      //             color: '#93CB79'
                      //         }
                      //     },
                      //     axisLabel: {
                      //         formatter: '{value}'
                      //     }
                      // },
                  ],
                  series: [
                      {
                          name: '延迟',
                          type: 'line',
                          data: y1,
                          symbol: 'none'
                      },
                      // {
                      //     name: 'up',
                      //     type: 'line',
                      //     data: y2,
                      //     symbol: 'none'
                      // }
                  ]
              };

              // 使用刚指定的配置项和数据显示图表。
              myChart.setOption(option);

          }

          // 刷新数据2
          var u1 = $.ajax({
              url: `/api/v1/prom/query_range?prom_id=${prom_id}&time_range=hour&query=probe_duration_seconds{instance="${instance}"}`,
          })

          // 刷新数据
          var u2 = $.ajax({
              url: `/api/v1/prom/query_range?prom_id=${prom_id}&time_range=hour&query=probe_success{instance="${instance}"}`,
          })


          $.when(u1, u2).then(function (a1, a2) {
              // console.log("a1 ", a1)
              // console.log("a2", a2)
              let date = [], data1 = [], data2 = [];
              let a1_values = a1[0].data.result[0].values
              let a2_values = a2[0].data.result[0].values
              for (let i = 0, len = a1_values.length; i < len; i++) {
                  // date.push(timestamp2time(a1_values[i][0]));
                  data1.push(parseFloat(a1_values[i][1]).toFixed(2));
              }
              for (let i = 0, len = a2_values.length; i < len; i++) {
                  date.push(timestamp2time(a2_values[i][0]));
                  data2.push(parseFloat(a2_values[i][1]).toFixed(2));
              }
              // console.log(date)
              // console.log(data1)
              // console.log(data2)
              draw(elemId, date, data1, data2)
          })
      }


      // 页面载入完毕后执行接口调用
      $(function () {
          // 获取所有集群列表，并填入select
          $.get('/api/cluster_list', function (data) {
              var clusters = data
              console.log(data)
              for (let i in clusters) {
                  $('#selectCluster').append('<option value="' + clusters[i].id + '">' + clusters[i].name + '</option>')
              }
              if (cluster_id > 0) {
                  $('#selectCluster').val(cluster_id)
                  refreshTable_v2(cluster_id)
                  let cluster_name = $('#selectCluster').find("option:selected").text();
                  // console.log("dddd:", cluster_name)
                  $('#cluster-name2').val(cluster_name)
              }
          })

          // 获取prom list，填充到modal的下拉列表中
          $.get('/api/prom/list', function (data) {
              console.log(data)
              for (let i in data.data) {
                  $('#selectProm').append('<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>')
              }
          })

          // 探测集群自身prom是否健康
          // /-/healthy
          $.get(`/api/v1/cluster/${cluster_id}/prom/healthy`, function (result) {
              console.log(result)
              if (result == 'ok') {
                  // 绘制从Prometheus获取的集群性能指标图形
                  let query_str_cluster_cpu = `100-(avg(rate(node_cpu_seconds_total{mode='idle'}[2m]))*100)`
                  let query_str_cluster_mem = `avg((1-node_memory_MemAvailable_bytes/node_memory_MemTotal_bytes))*100`
                  let query_str_cluster_disk = encodeURIComponent(`avg((node_filesystem_size_bytes{fstype=~'ext.?|xfs'}-node_filesystem_free_bytes{fstype=~'ext.?|xfs'})*100/(node_filesystem_avail_bytes{fstype=~'ext.?|xfs'}+(node_filesystem_size_bytes{fstype=~'ext.?|xfs'}-node_filesystem_free_bytes{fstype=~'ext.?|xfs'})))`)
                  let query_str_cluster_net_in = encodeURIComponent('sum(irate(container_network_receive_bytes_total{namespace=~".+"}[2m]))/1024')
                  let query_str_cluster_net_out = encodeURIComponent('sum(irate(container_network_transmit_bytes_total{namespace=~".+"}[2m]))/1024')
                  drawGauge(query_str_cluster_cpu, 'chart_cpu', 'CPU平均使用率')
                  drawGauge(query_str_cluster_mem, 'chart_mem', '内存平均使用率')
                  drawGauge(query_str_cluster_disk, 'chart_disk', '磁盘平均使用率')
                  draw2Lines(query_str_cluster_net_in, query_str_cluster_net_out, 'chart_net', '网络流量(kbps)')
                  // 绘制从Prometheus获取的集群信息
                  let query_nodes_count = 'count(kube_node_info)'
                  let query_cpu_cores = 'sum(machine_cpu_cores)'
                  let query_mem = 'ceil(sum(machine_memory_bytes)/1024/1024/1024)'
                  let query_disk = "ceil(sum(node_filesystem_size_bytes{fstype=~'ext.?|xfs'})/1024/1024/1024)"
                  let query_running_pods = 'sum(kubelet_running_pod_count)'
                  let query_pods = 'sum(kube_node_status_allocatable_pods)'
                  let query_service = 'sum(kube_service_info)'
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_nodes_count}`, function (result) {
                      // console.log(result)
                      $('#nodes').text(result.data.result[0].value[1])
                  })
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_cpu_cores}`, function (result) {
                      // console.log(result)
                      $('#cores').text(result.data.result[0].value[1])
                  })
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_mem}`, function (result) {
                      // console.log(result)
                      $('#memory_size').text(result.data.result[0].value[1] )
                  })
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_disk}`, function (result) {
                      // console.log(result)
                      $('#disk_size').text(result.data.result[0].value[1])
                  })
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_service}`, function (result) {
                      // console.log(result)
                      $('#services').text(result.data.result[0].value[1])
                  })
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_running_pods}`, function (result) {
                      // console.log(result)
                      $('#running_pods').text(result.data.result[0].value[1])
                  })
                  $.get(`/api/v1/cluster/${cluster_id}/prom/query?query=${query_pods}`, function (result) {
                      // console.log(result)
                      $('#pods').text("/" + result.data.result[0].value[1])
                  })
                  // 绘制mysql监控信息
                  $('#table_mysql').DataTable({
                      ajax: `/api/v1/cluster/${cluster_id}/prom/mysql_mon_info`,
                      columns: [
                          {data: 'instance'},
                          {data: 'uptime'},
                          {data: 'qps'},
                          {data: 'conn'},
                          {data: 'slow'},
                          {data: 'net_in'},
                          {data: 'net_out'},
                      ],
                      processing: true,
                      language: {
                          "url": "/static/language.json"
                      },
                      lengthChange: false,
                      searching: false,
                      paging: false
                  });


              }
          });


          // 绘制本集群所关联的instance的可行性图形
          let url_endpoints = `/api/v1/cluster/get_instance?cluster_id=${cluster_id}`
          $.get(url_endpoints, function (data) {
              console.log(data)
              // 遍历
              for (let i in data.data) {
                  // console.log(data.data[i].instance)
                  let endpoint_grah_html = `          <div class="col-lg-2">
            <p><b>站点可用性：</b></p>
            <p>1H <span id="aval_1h_${i}"></span>%</p>
            <p>1D <span id="aval_1d_${i}"></span>%</p>
            <p>1W <span id="aval_1w_${i}"></span>%</p>
          </div>
          <div class="col-lg-10">
            <div id="chart_main_${i}" style="height:200px"></div>
          </div>`

                  $('#prom_aval_box').append(endpoint_grah_html)

                  // 测试，获取某一个Endpoint的黑盒监控数据，并画出图形
                  let instance = data.data[i].instance
                  let prom_id = data.data[i].prom_id
                  let query_str_aval_1h = `avg_over_time(probe_success{instance="${instance}"}[1h])*100`
                  let query_str_aval_1d = `avg_over_time(probe_success{instance="${instance}"}[1d])*100`
                  let query_str_aval_1w = `avg_over_time(probe_success{instance="${instance}"}[1w])*100`
                  // $(`#site_name_${i}`).text(instance)
                  updateAvalNumber(prom_id, query_str_aval_1h, `aval_1h_${i}`)
                  updateAvalNumber(prom_id, query_str_aval_1d, `aval_1d_${i}`)
                  updateAvalNumber(prom_id, query_str_aval_1w, `aval_1w_${i}`)
                  drawAvalLines(prom_id, `chart_main_${i}`, instance)
              }
          })

      })

  </script>
{% endblock %}